/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.customer;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.util.MapToBeanUtils;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ReturnVisitCustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.CustomerRecord;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitCustomer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitRecord;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 客户回访管理业务处理层
 * @ClassName: ReturnVisitCustomerService
 * @author 钟鑫
 * @Date: 2017年11月16日 09:47:14
 * @Version V1.0
 */
@Service
public class ReturnVisitCustomerService extends BaseService {

    @Autowired
    private ReturnVisitCustomerDao returnVisitCustomerDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private CustomerRecordService customerRecordService;

    @Autowired
    private KeyWorker keyWorker;

    /**
     * 查询未回访、待回访客户列表
     * @param map 参数
     *            queryType：查询分类（NO：未回访，WAIT:待回访）空为查询全部
     * @return 结果集合
     */
    public List<Map> queryReturnVisitCustomerList(Map map){
        return returnVisitCustomerDao.queryReturnVisitCustomerList(map);
    }

    /**
     * 查询未回访、待回访客户列表统计数量
     * @param map 参数
     *            queryType：查询分类（NO：未回访，WAIT:待回访）空为查询全部
     * @return 结果集合
     */
    public Integer countReturnVisitCustomerList(Map map){
        return returnVisitCustomerDao.countReturnVisitCustomerList(map);
    }
    /**
     * 查询未回访统计数量
     * @param map 参数
     *            queryType：查询分类（NO：未回访）空为查询全部
     * @return 结果集合
     */
    public Integer getCountReturnVisitCustomerList(Map map){
        return returnVisitCustomerDao.getCountReturnVisitCustomerList(map);
    }

    /**
     * 新增或修改回访客户信息
     * @param returnVisitCustomer 回访客户对象
     */
    public void saveOrUpdateReturnVisitCustomer(ReturnVisitCustomer returnVisitCustomer){
        if (null == returnVisitCustomer){
            throw new BizException("回访客户对象为空，无法操作", 10001);
        }
        if (null == returnVisitCustomer.getCustomerId()){
            throw new BizException("客户id为空，无法操作", 10001);
        }
        if (null == returnVisitCustomer.getLastBusId()){
            throw new BizException("商机id为空，无法操作", 10001);
        }
        ReturnVisitCustomer condition = new ReturnVisitCustomer();
        condition.setCustomerId(returnVisitCustomer.getCustomerId());
        condition.setLastBusId(returnVisitCustomer.getLastBusId());
        ReturnVisitCustomer oldReturnVisitCustomer = repository.get(condition);
        if (null == oldReturnVisitCustomer){
            // 如果未传递创建人和修改人
            if (null == returnVisitCustomer.getCreaterId()){
                returnVisitCustomer.setCreateUser(SessionManager.getCurrentUser());
            }
            if (null == returnVisitCustomer.getUpdaterId()) {
                returnVisitCustomer.setUpdaterUser(SessionManager.getCurrentUser());
            }
            returnVisitCustomer.setId(keyWorker.nextId());
            repository.save(returnVisitCustomer);
        } else {
            // 如果未传递修改人
            if (null == returnVisitCustomer.getUpdaterId()) {
                oldReturnVisitCustomer.setUpdaterUser(SessionManager.getCurrentUser());
            } else {
                oldReturnVisitCustomer.setUpdateTime(returnVisitCustomer.getUpdateTime());
                oldReturnVisitCustomer.setUpdaterId(returnVisitCustomer.getUpdaterId());
                oldReturnVisitCustomer.setUpdaterName(returnVisitCustomer.getUpdaterName());
                oldReturnVisitCustomer.setUpdaterOrgId(returnVisitCustomer.getUpdaterOrgId());
            }
            oldReturnVisitCustomer.setCustomerId(returnVisitCustomer.getCustomerId());
            oldReturnVisitCustomer.setLastBusId(returnVisitCustomer.getLastBusId());
            repository.saveOrUpdate(oldReturnVisitCustomer);
        }
    }

    /**
     * 客户回访分配
     * @param map
     */
    public void saveAllot(Map map) {
        User loginUser =  SessionManager.getCurrentUser();
        String loginUserName = loginUser.getName()+loginUser.getLoginName();
        Long returnVisitId = Long.parseLong(map.get("returnVisitId").toString());
        String returnVisitName = (String) map.get("returnVisitName");
        Long returnVisitOrgId = Long.parseLong(map.get("returnVisitOrgId").toString());

        List<Map> resultList = new ArrayList<Map>();
        // 获取选中的id
        if (null != map.get("ids")){
            resultList = returnVisitCustomerDao.queryByIds(map.get("ids").toString());
        } else {
            Integer allotNum = Integer.parseInt(map.get("allotNum").toString());
            map.put("start",0);
            map.put("limit",allotNum);
            resultList =  returnVisitCustomerDao.queryReturnVisitCustomerList(map);
        }

        // 循环保存
        if (CollectionUtils.isNotEmpty(resultList)){
            Long customerid = null;
            ReturnVisitCustomer returnVisitCustomer = null;
            Customer customer = null;
            Business business = null;
            Map customerRecordMap = null;
            for (Map result : resultList){
                // 客户
                customer = repository.get(Customer.class,Long.parseLong(result.get("customerid").toString()));
                customer.setUpdaterUser(loginUser);
                customer.setLastReturnVisiterId(returnVisitId);
                customer.setLastReturnVisiterName(returnVisitName);
                customer.setLastReturnVisiterOrgId(returnVisitOrgId);
                repository.saveOrUpdate(customer);

                // 商机
                business = repository.get(Business.class,Long.parseLong(result.get("businessid").toString()));
                business.setUpdaterUser(loginUser);
                business.setReturnVisitId(returnVisitId);
                repository.saveOrUpdate(business);

                // 回访客户表
                returnVisitCustomer = repository.get(ReturnVisitCustomer.class,Long.parseLong(result.get("id").toString()));
                returnVisitCustomer.setReturnVisitId(returnVisitId);
                returnVisitCustomer.setReturnVisitName(returnVisitName);
                returnVisitCustomer.setAllotId(loginUser.getId());
                returnVisitCustomer.setAllotName(loginUserName);
                returnVisitCustomer.setUpdaterUser(loginUser);
                repository.saveOrUpdate(returnVisitCustomer);
                // 客户操作记录表
                customerRecordMap = new HashMap();
                customerRecordMap.put("cusId",customer.getId());
                customerRecordMap.put("tableName",Customer.TABLE_NAME);
                customerRecordMap.put("tableId",customer.getId());
                customerRecordMap.put("recordType",CustomerRecordConstant.CUS_VISIT_ALLOT);
                customerRecordMap.put("operateUser",loginUser.getId());
                customerRecordMap.put("content","将未回访客户分配给客服");
                customerRecordMap.put("ext3",customer.getNo());
                customerRecordService.saveCustomerRecord(customerRecordMap);
            }
        } else {
            throw  new BizException("当前没有未回访数据进行分配",BizException.DEFAULT_CODE);
        }
    }

    /**
     * 回访记录保存
     * @param paramMap
     */
    public void saveVisitResult(Map<String, Object> paramMap) {
        User loginUser =  SessionManager.getCurrentUser();
        Long id = Long.parseLong(paramMap.get("id").toString());
        String visitResultCode = paramMap.get("visitResultCode").toString();
        String visitResultName = paramMap.get("visitResultName").toString();
        String resultReasonCode = null;
        if (null != paramMap.get("resultReasonCode")){
            resultReasonCode = paramMap.get("resultReasonCode").toString();
        }
        String resultReasonDescription = paramMap.get("resultReasonDescription").toString();
        ReturnVisitCustomer returnVisitCustomer = repository.get(ReturnVisitCustomer.class,id);
        if (null == returnVisitCustomer){
            throw  new BizException("当前回访数据不存在！",BizException.DEFAULT_CODE);
        }
        // 客户
        Customer customer = repository.get(Customer.class,returnVisitCustomer.getCustomerId());
        customer.setUpdaterUser(loginUser);
        customer.setLastReturnVisiterId(loginUser.getId());
        customer.setLastReturnVisiterName(loginUser.getName()+loginUser.getLoginName());
        customer.setLastReturnVisiterOrgId(loginUser.getOrgId());
        customer.setLastReturnVisitTime(new Date());
        repository.saveOrUpdate(customer);

        // 商机
        Business business = repository.get(Business.class,returnVisitCustomer.getLastBusId());
        business.setUpdaterUser(loginUser);
        business.setLastReturnVisitTime(new Date());
        repository.saveOrUpdate(business);

        // 客户操作记录表
        Map customerRecordMap = new HashMap();
        customerRecordMap.put("cusId",customer.getId());
        customerRecordMap.put("tableName",Customer.TABLE_NAME);
        customerRecordMap.put("tableId",customer.getId());
        customerRecordMap.put("recordType",CustomerRecordConstant.CUS_VISIT);
        customerRecordMap.put("operateUser",loginUser.getId());
        customerRecordMap.put("content","客服回访客户");
        customerRecordMap.put("ext3",customer.getNo());
        customerRecordService.saveCustomerRecord(customerRecordMap);

        // 回访记录表
        ReturnVisitRecord returnVisitRecord = new ReturnVisitRecord();
        BeanUtils.copyProperties(returnVisitCustomer,returnVisitRecord,"id");
        returnVisitRecord.setId(keyWorker.nextId());
        returnVisitRecord.setCreateUser(loginUser);
        returnVisitRecord.setUpdaterUser(loginUser);
        returnVisitRecord.setBusId(returnVisitCustomer.getLastBusId());
        returnVisitRecord.setBusStatus(business.getBusinessStatus());
        returnVisitRecord.setReturnVisitId(loginUser.getId());
        returnVisitRecord.setReturnVisitName(loginUser.getName()+loginUser.getLoginName());
        returnVisitRecord.setVisitResultCode(visitResultCode);
        returnVisitRecord.setVisitResultName(visitResultName);
        returnVisitRecord.setResultReasonCode(resultReasonCode);
        returnVisitRecord.setResultReasonDescription(resultReasonDescription);
        returnVisitRecord.setBusStatus(business.getBusinessStatus());
        repository.save(returnVisitRecord);

        // 删除回访表中数据
        repository.delete(returnVisitCustomer);
    }

    /**
     * 查询已回访客户
     * @param paramMap 参数列表
     * @return 查询结果
     */
    public List<Map> queryAlreadyReturnVisitList(Map<String, Object> paramMap) {
        List<Map> returnVisitRecordList = returnVisitCustomerDao.queryAlreadyReturnVisitList(paramMap);
        if (CollectionUtils.isNotEmpty(returnVisitRecordList)){
            // 判断有没有建立新商机
            Business business = null;
            for (Map returnVisitRecord : returnVisitRecordList){
                // 如果有新商机，查询出新商机的id和商机编号
                if (null != returnVisitRecord.get("lastbusinessid") && !returnVisitRecord.get("businessid").equals(returnVisitRecord.get("lastbusinessid"))){
                    business = repository.get(Business.class,Long.parseLong(returnVisitRecord.get("lastbusinessid").toString()));
                    // 如果新商机的创建人和当前回访人相等
                    if (business.getCreaterId().longValue() == Long.parseLong(returnVisitRecord.get("returnvisitid").toString())){
                        returnVisitRecord.put("lastbusinessno",business.getNo());
                    }
                }
            }
        }
        return returnVisitRecordList;
    }

    /**
     * 查询已回访客户列表统计数量
     * @param map 参数
     * @return 统计结果
     */
    public Integer countAlreadyReturnVisitList(Map map){
        return returnVisitCustomerDao.countAlreadyReturnVisitList(map);
    }

    /**
     * 查询已回访客户
     * @param paramMap 参数列表
     * @return 查询结果
     */
    public List<Map> queryAlreadyCustomerReturnVisitList(Map<String, Object> paramMap) {
        List<Map> returnVisitRecordList = returnVisitCustomerDao.queryAlreadyCustomerReturnVisitList(paramMap);
//        if (CollectionUtils.isNotEmpty(returnVisitRecordList)){
//            // 判断有没有建立新商机
//            Business business = null;
//            for (Map returnVisitRecord : returnVisitRecordList){
//                // 如果有新商机，查询出新商机的id和商机编号
//                if (null != returnVisitRecord.get("lastbusinessid") && !returnVisitRecord.get("businessid").equals(returnVisitRecord.get("lastbusinessid"))){
//                    business = repository.get(Business.class,Long.parseLong(returnVisitRecord.get("lastbusinessid").toString()));
//                    // 如果新商机的创建人和当前回访人相等
//                    if (business.getCreaterId().longValue() == Long.parseLong(returnVisitRecord.get("returnvisitid").toString())){
//                        returnVisitRecord.put("lastbusinessno",business.getNo());
//                    }
//                }
//            }
//        }
        return returnVisitRecordList;
    }

    /**
     * 查询已回访客户列表统计数量
     * @param map 参数
     * @return 统计结果
     */
    public Integer countAlreadyCustomerReturnVisitList(Map map){
        return returnVisitCustomerDao.countAlreadyCustomerReturnVisitList(map);
    }

    /**
     * 根据回访结果及跟进人组织id统计
     * @param map 参数
     * @return 统计结果
     */
    public Integer countByResultAndFollowerOrgIds(Map map){
        return returnVisitCustomerDao.countByResultAndFollowerOrgIds(map);
    }
}
